The Life Cycle of a Servlet
Three methods are central to the life cycle of a servlet:
init( ),
service( ),
and destroy( ).
They are implemented by every servlet and are invoked at a specific time by the server. Consider next a typical user scenario, to understand when these methods are called.
First, assume that a user enters a Uniform Resource Locator (URL) to a Web browser. The browser then generates an HTTP request for this URL and sends it to the appropriate server.
Second, this HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.
Third, the server invokes the init ( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. You will see that initialization parameters can be passed to the servlet so that it may configure itself.
Syntax: public void init(ServletConfig config)throws ServletException
Fourth, the server invokes the servlet's service( ) method, which is called to process the HTTP request. You will see that the servlet can read data that has been provided in the HTTP request, and may also formulate an HTTP response for the client.
Syntax:-public void service(ServletRequest req,ServletResponse res) throws Servletexception,IOException
The servlet remains in the server's address space and is available to process any other
HTTP requests received from clients. The service ( ) method is called for each HTTP
Request.
Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy () method to relinquish any resources, such as file handles that are allocated for the servlet.
Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage –collected.
Syntax:- public void destroy()